// AviFile.cpp: implementation of the CAviFile class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "AviFile.h"

#include <stdlib.h>
#include <process.h>
#include <stdio.h>
#include "DebugInfo.h"
#include "mmsystem.h"

//#ifdef _DEBUG
//#undef THIS_FILE
//static char THIS_FILE[]=__FILE__;
//#define new DEBUG_NEW
//#endif

static int adpcm_step[89] =
{
  7, 8, 9, 10, 11, 12, 13, 14, 16, 17,
  19, 21, 23, 25, 28, 31, 34, 37, 41, 45,
  50, 55, 60, 66, 73, 80, 88, 97, 107, 118,
  130, 143, 157, 173, 190, 209, 230, 253, 279, 307,
  337, 371, 408, 449, 494, 544, 598, 658, 724, 796,
  876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066,
  2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358,
  5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899,
  15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767
};

static int adpcm_index[16] =
{
  -1, -1, -1, -1, 2, 4, 6, 8,
  -1, -1, -1, -1, 2, 4, 6, 8
};

static int ms_adapt_table[] =
{
  230, 230, 230, 230, 307, 409, 512, 614,
  768, 614, 512, 409, 307, 230, 230, 230
};

static int ms_adapt_coeff1[] =
{
  256, 512, 0, 192, 240, 460, 392
};

static int ms_adapt_coeff2[] =
{
  0, -256, 0, 64, 0, -208, -232
};

//adpcm
#define MS_IMA_ADPCM_PREAMBLE_SIZE 4
#define MS_ADPCM_PREAMBLE_SIZE 6

#define SE_16BIT(x)  if (x & 0x8000) x -= 0x10000;
// useful macros
// clamp a number between 0 and 88
#define CLAMP_0_TO_88(x)  if (x < 0) x = 0; else if (x > 88) x = 88;
// clamp a number within a signed 16-bit range
#define CLAMP_S16(x)  if (x < -32768) x = -32768;   else if (x > 32767) x = 32767;
// clamp a number above 16
#define CLAMP_ABOVE_16(x)  if (x < 16) x = 16;
// sign extend a 16-bit value
#define SE_16BIT(x)  if (x & 0x8000) x -= 0x10000;
// sign extend a 4-bit value
#define SE_4BIT(x)  if (x & 0x8) x -= 0x10;
#define LE_16(x) ((x)[0]+(256*((x)[1])))



#define  IDS_CHANGE_FAILED	100

//extern		HANDLE		g_hDllModule;

#define		GET_EXIT()	if(GetExit())	\
						{				\
							break;		\
						}				\
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CAviFile::CAviFile()
{
	memset(m_dp, 0, sizeof(m_dp));
	memset(m_lastframe, 0, sizeof(m_lastframe));
	memset(m_file_size1, 0, sizeof(m_file_size1));
	memset(m_file_size2, 0, sizeof(m_file_size2));
	memset(m_lTotalFrames, 0, sizeof(m_lTotalFrames));



	m_strSFileName = "";
	for(int i = 0; i< 4; i++)
	{
		m_pDFileHandle[i] = NULL;
		m_iTvSystem[i] = '0';
		m_iQuality[i] = '0';
		m_iFrameRate[i] = '0';
	}
	m_pSFileHandle = NULL;
	m_iFileNum = 1;

	m_hThreadHandle = NULL;
	m_dwThreadID = 0;
	m_hExit = ::CreateEvent(NULL, TRUE, FALSE, NULL);

	m_bPCMSound = TRUE;
	m_bWriteFlag = FALSE;
	m_bDistChannel = FALSE;

	m_bChanging = FALSE;

	m_eChangeType = E_CHANGE_AVI;

	memset(m_szAviHeader, 0, AVI_HEADER_SIZE);
	m_lHeaderSize = AVI_HEADER_SIZE;

	memset(m_szBuffer, 0, MAX_BUFFER_SIZE);
	m_lDataSize = 0;
	m_lBufferSize = MAX_BUFFER_SIZE;
	m_lCurBufferPos = 0;

	m_bIsAudio = TRUE;
}

CAviFile::~CAviFile()
{
	if(m_hThreadHandle)
	{
		CloseHandle(m_hThreadHandle);
		m_hThreadHandle = NULL;
		m_dwThreadID = 0;
	}

	if(m_hExit)
	{
		CloseHandle(m_hExit);
		m_hExit = NULL;
	}
	
	CloseDFileHandle();

	if(m_pSFileHandle)
	{
		fclose(m_pSFileHandle);
		m_pSFileHandle = NULL;
	}
}

//---------------------------------------------------------------------
//说明：打开文件，同时取得帧率制式等信息
//参数：[IN]lpFileName:源文件的名称
//		[in]iFileNum:转换后文件的个数
//返回：成功返回TRUE，失败返回FALSE
//---------------------------------------------------------------------
BOOL CAviFile::OpenFile(LPCSTR lpFileName, int& iFileNum)
{
	m_strSFileName = lpFileName;
	if(GetInfo())
	{
		iFileNum = m_iFileNum;

		//取得AVI去降后缀名的名称的文件
		int iPos = m_strSFileName.rfind('\\');
		if(iPos > 0)
		{
			m_strAviName = m_strSFileName.substr( iPos + 1, m_strSFileName.size());
			m_strAviName = m_strAviName.substr(0, m_strAviName.size() - 4);
		}
		else
		{
			return FALSE;
		}
		//设置临时文件的名称信息
		string strAppPath = GetAppPath();
		for(int i = 0 ; i < MAX_FILE_NUM ; i++)
		{
			char szTemp[MAX_PATH] = {0};
			sprintf(szTemp, "%s%sa_1_%d.tmp", strAppPath.c_str(), m_strAviName.c_str(), i+1);
			m_strTFileHead[i] = szTemp;
			//m_strTFileHead[i].Format("%s%sa_1_%d.avi", GetAppPath(), m_strAviName, i+1);
			memset(szTemp, 0, sizeof(szTemp));
			sprintf(szTemp, "%s%sa_2_%d.tmp", strAppPath.c_str(), m_strAviName.c_str(), i+1);
			m_strTFileBody[i] = szTemp;
			//m_strTFileBody[i].Format("%s%sa_2_%d.avi", GetAppPath(), m_strAviName, i+1);//
			memset(szTemp, 0, sizeof(szTemp));
			sprintf(szTemp, "%s%sa_3_%d.tmp", strAppPath.c_str(), m_strAviName.c_str(), i+1);
			m_strTFileTail[i] = szTemp;
			//m_strTFileTail[i].Format("%s%sa_3_%d.avi", GetAppPath(), m_strAviName, i+1);
			memset(szTemp, 0, sizeof(szTemp));
			sprintf(szTemp, "%s%s_tmp%d.tmp", strAppPath.c_str(), m_strAviName.c_str(), i+1);
			m_strTempFile[i] = szTemp;
			//m_strTempFile[i].Format("%s%stmp%d.avi", GetAppPath(), m_strAviName, i+1);
		}
		return TRUE;
	}
	return FALSE;
}

//---------------------------------------------------------------------------
//说明：设置转换类型,如果不调用则默认转换成AVI
//参数：[in]iType:0表示转换成AVI,1表示转成其它格式
//返回：成功返回TRUE，失败返回FALSE
//---------------------------------------------------------------------
BOOL CAviFile::SetChangeType(int iType)
{
	if(0 == iType)
	{
		m_eChangeType = E_CHANGE_AVI;
	}
	else if( 1 == iType)
	{
		m_eChangeType = E_CAHNGE_MPEG;
	}

	return TRUE;
}

//---------------------------------------------------------------------
//说明：取得帧率等信息，同时返回转换后的文件个数，在打开文件后调用
//参数：无
//返回：成功返回TRUE，失败返回FALSE
//---------------------------------------------------------------------
BOOL CAviFile::GetInfo()
{
	return FALSE;
}

//---------------------------------------------------------------------
//说明：创建目标文件
//参数：[in]iChID:通道索引0-3
//返回：成功返回TRUE，失败返回FALSE
//---------------------------------------------------------------------
BOOL CAviFile::CreateDeskFile(int iChID)
{	
	string strType;
	if(E_CHANGE_AVI == m_eChangeType)
	{
		strType = ".avi";
	}
	else
	{
		strType = ".mpeg";
	}
/*
	char szTemp[MAX_PATH] = {0};
	if(m_bDistChannel)
	{
		sprintf(szTemp, "%s\\%s_%d%s", m_strFolder.c_str(), m_strAviName.c_str(), iChID + 1, strType.c_str());
		//m_strDFileName[iChID].Format("%s\\%s_%d%s", m_strFolder, m_strAviName, iChID + 1, strType);
	}
	else
	{
		sprintf(szTemp, "%s\\%s%s", m_strFolder.c_str(), m_strAviName.c_str(), strType.c_str());
		//m_strDFileName[iChID].Format("%s\\%s%s", m_strFolder, m_strAviName, strType);
	}
	m_strDFileName[iChID] = szTemp;
//*/
	m_strDFileName[iChID] = m_strFolder;

	m_pDFileHandle[iChID] = fopen(m_strDFileName[iChID].c_str(), "wb");
	if(m_pDFileHandle[iChID] ==  NULL)
	{
		DebugMsg("OpenDeskFile Failed\n");
		//MyPostMessage(m_hWnd, m_nMsgID, -1, E_OPEN_DESKFILE);
		return FALSE;
	}

	return TRUE;
}

//---------------------------------------------------------------------
//说明：创建AVI文件头，创建由63xx为基准的头文件，如果不同设备不一样之处
//		在程序末尾处调用ModifyHeader()由不同子类进行不同的处理
//参数：[in]iChID:表示读取第几个通道的数据 0-3
//返回：成功返回TRUE，失败返回FALSE
//---------------------------------------------------------------------
BOOL CAviFile::CreateAviHeader(int iChID, BOOL bIsAudio)
{	
	FILE* d_fp;
	unsigned char *stream;
	unsigned short tmp;
	int i;

	unsigned char header_tb1[] = {
			0x52,0x49,0x46,0x46,0x04,0x17,0x1c,0x00,0x41,0x56,0x49,0x20,0x4c,0x49,0x53,0x54,				
			0x26,0x01,0x00,0x00,0x68,0x64,0x72,0x6c,0x61,0x76,0x69,0x68,0x38,0x00,0x00,0x00,				
			0xb5,0x4e,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x01,0x00,0x00,		
			0x4c,0x51,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x0a,0x00,	
			0xc0,0x02,0x00,0x00,0xe0,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,		
			0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x4c,0x49,0x53,0x54,0x74,0x00,0x00,0x00,		
			0x73,0x74,0x72,0x6c,0x73,0x74,0x72,0x68,0x38,0x00,0x00,0x00,0x76,0x69,0x64,0x73,		
			0x48,0x32,0x36,0x35,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, // H265
			0xb5,0x4e,0x00,0x00,0x40,0x42,0x0f,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,			
			0x00,0x7d,0x00,0x00,0xff,0xff,0xff,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,			
			0xc0,0x02,0xe0,0x01,0x73,0x74,0x72,0x66,0x28,0x00,0x00,0x00,0x28,0x00,0x00,0x00,		
			0xc0,0x02,0x00,0x00,0xe0,0x01,0x00,0x00,0x01,0x00,0x10,0x00,0x48,0x32,0x36,0x35, // H265		
			0x00,0x78,0x0f,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,		
			0x00,0x00,0x00,0x00,0x4c,0x49,0x53,0x54,0x5e,0x00,0x00,0x00,0x73,0x74,0x72,0x6c,		
			0x73,0x74,0x72,0x68,0x38,0x00,0x00,0x00,0x61,0x75,0x64,0x73,0x00,0x00,0x00,0x00,		
			0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x02,0x00,0x00,0x00,		
			0xd0,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x27,0x00,0x00,		
			0xff,0xff,0xff,0xff,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,		
			0x73,0x74,0x72,0x66,0x12,0x00,0x00,0x00,0x45,0x00,0x01,0x00,0x40,0x1f,0x00,0x00,		
			0xd0,0x07,0x00,0x00,0x01,0x00,0x02,0x00,0x00,0x00,0x4a,0x55,0x4e,0x4b,0xbe,0x06,		
			0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
			0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
			0xff,
	};

	
	unsigned char header_tbl1[] = {
		0x4c,0x49,0x53,0x54,0x00,0x00,0x00,0x00,
			0x6d,0x6f,0x76,0x69,
			0xff
	};
	
	stream = (unsigned char *)malloc(0x1000);
	if(stream == NULL)
	{
		DebugMsg("Memory not enough\n");
		return FALSE;
	}

	m_strTFileHead[iChID] = "H:\\temp_convert.avih";
	d_fp = fopen(m_strTFileHead[iChID].c_str(), "wb");
	if(d_fp == NULL)
	{
		DebugMsg("Open File Failed\n");
		free(stream);
		return FALSE;
	}

	m_iTvSystem[iChID] = 'P';
	m_iQuality[iChID] = '5';   // 1-D1，2-HD1，3-CIF，4-QCIF  5-高清
	m_iFrameRate[iChID] = 25;

	ModifyHeader(header_tb1, sizeof(header_tb1), iChID);

	//// 有音频
	//if (bIsAudio)
	//{
	//	header_tb1[16] = 0x26;
	//	header_tb1[17] = 0x01;
	//	header_tb1[56] = 0x02;
	//}
	//else// 无音频
	{
		header_tb1[16] = 0xC0;
		header_tb1[17] = 0x00;
		header_tb1[56] = 0x01;
	}

	for(i=0;i<0x158;i++)
		*(stream+i) = header_tb1[i];

	for(i=0x158;i<0x800;i++) // 0x7f4 cywang
		*(stream+i) = 0x00;

	tmp = 0;	
	for(i=0x800;i<0x80c;i++) // 0x7f4 0x800 cywang
		*(stream+i) = header_tbl1[tmp++];
	
	//写文件头
	fwrite(stream,1,0x80c,d_fp); // 0x800
	fclose(d_fp);
	
	free(stream);

	return TRUE;
}

//---------------------------------------------------------------------
//说明：转换AVI文件
//参数：无
//返回：成功返回TRUE，失败返回FALSE
//---------------------------------------------------------------------
BOOL CAviFile::CreateAviFrameFile(int iChID)
{
	m_strTFileBody[iChID] = "H:\\temp_convert.avib";
	m_dp[iChID] = fopen(m_strTFileBody[iChID].c_str(), "wb");
	m_lastframe[iChID] = 0;
	m_file_size2[iChID] = 0;
	m_file_size1[iChID] = 0;

	return TRUE;
}

BOOL CAviFile::WriteAviFrame(int iChID, int frame_type, byte* byData, int data_len)
{
	m_lastframe[iChID] = data_len;
	m_file_size1[iChID] = m_file_size2[iChID];

	char szHead[8] = { 0 };
	if (frame_type == 1) //i frame
		memcpy(szHead, "00db", 4);
	else if(frame_type == 2)// p frame
		memcpy(szHead, "00dc", 4);
	else if(frame_type == 3)
		memcpy(szHead, "01wb", 4);

	*(int*)(szHead + 4) = data_len;
	fwrite(szHead, 1, 8, m_dp[iChID]);
	fwrite(byData, 1, data_len, m_dp[iChID]);

	m_file_size2[iChID] += 8 + data_len;
	m_lTotalFrames[iChID]++;

	return TRUE;
}

BOOL CAviFile::CloseAviFrame(int iChID)
{
	if (m_dp[iChID] == NULL)
		return TRUE;

	//修正最后一帧数据， 因为整个大小 4字节对齐
	int mod = m_file_size2[iChID] % 4;
	m_lastframe[iChID] -= mod;
	m_file_size2[iChID] -= mod;

	fseek(m_dp[iChID], m_file_size1[iChID] + 4, SEEK_SET);
	fwrite(&m_lastframe[iChID], 1, 4, m_dp[iChID]);

	if (m_dp[iChID])
	{
		fclose(m_dp[iChID]);
		m_dp[iChID] = NULL;
	}

	return TRUE;
}

BOOL CAviFile::CreateAviFile()
{
	FILE *d_fp[MAX_FILE_NUM] = {0};
	FILE *fp[MAX_FILE_NUM] = {0};
	unsigned long length=0;
	unsigned long packet_size=0;			//帧大小
	unsigned long i(0);
	unsigned long file_size1[MAX_FILE_NUM] = {0};			
	unsigned long file_size2[MAX_FILE_NUM] = {0};			//文件长度
	unsigned long lastframe[MAX_FILE_NUM] = {0};			//最后一帧
	unsigned long tmp_packet_flag = 0;						//临时包的标志
	
	int			iFrameChID = 0;								//当前帧对应的通道ID
	BOOL		bOpenOK = TRUE;								//打开临时文件是否正常
	
	m_pSFileHandle = fopen(m_strSFileName.c_str(),"rb");
	if(m_pSFileHandle == NULL)
	{
		return FALSE;
	}
	
	int iFileTotalLen(0);	//文件长度
	fseek(m_pSFileHandle, 0, SEEK_END);
	iFileTotalLen = ftell(m_pSFileHandle);
	fseek(m_pSFileHandle, 0, SEEK_SET);
	if(0 == iFileTotalLen)
	{
		fclose(m_pSFileHandle);
		m_pSFileHandle = NULL;
		return FALSE;
	}
	
	for(int j = 0 ; j < m_iFileNum ; j ++)
	{
		m_lTotalFrames[j] = 0;
		m_lTotalLengthAudio[j] = 0;
		d_fp[j] = fopen(m_strTempFile[j].c_str(), "wb+rb");
		if(d_fp[j] == NULL)
		{
			bOpenOK = FALSE;
			break;
		}
	}
	
	if(!bOpenOK)
	{
		for(int j = 0 ; j < m_iFileNum ; j++)
		{
			if(d_fp[j])
			{
				fclose(d_fp[j]);
				d_fp[j] = NULL;
			}
		}
		fclose(m_pSFileHandle);
		m_pSFileHandle = NULL;
		return FALSE;
	}
	
	int					iCurFilePos = 0;			//当前文件指针的位置
	int					findoff = 0;				//查找帧数据时候的偏移位置
	int					AddInfoLenth = 0;			//偏移位置
	int					iOffset = 0;				//帧数据的偏移位置
	int					iFrameType = 0;				//帧类型
	int					iFrameLen = 0;				//帧长度		
	FrameHead*			pFrame = NULL;				//帧结构定义
	unsigned	char	szAudioBuffer[AUDIO_BUFFER_SIZE] = {0};	//音频数据
	int					iAudioSize = AUDIO_BUFFER_SIZE;			//音频数据的长度
	BOOL				bWriteDecodeAudioBuffer = FALSE;		//是否写解码后的音频数据
	while(1)
	{
		//判断是否退出
		GET_EXIT()
			
		if(!ReadFileData())
		{
			DebugMsg("read file over\n");	
			break;
		}
		
		iCurFilePos = ftell(m_pSFileHandle);
		MyPostMessage( 0, (long)(5 + 30.0*iCurFilePos/iFileTotalLen)); 
		

		while(m_lCurBufferPos < m_lDataSize)
		{
			//判断是否退出
			GET_EXIT()

			//dvr中会把一个帧凑为8的倍数。
			if(m_lCurBufferPos%8)
			{
				int off = m_lCurBufferPos%8;
				off = 8 - off;
				m_lCurBufferPos += off;
			}

			if(MoveNextFrameHead(m_szBuffer+m_lCurBufferPos, m_lDataSize-m_lCurBufferPos ,&findoff))
			{
				//判断是否退出
				GET_EXIT()
				
				m_lCurBufferPos += findoff;
				m_lCurBufferPos -= 4;
				
				pFrame = (FrameHead *)(m_szBuffer+m_lCurBufferPos);
				//pFrame->iFrameLen = pFrame->iFrameLen&0x00ffffff;

				if(m_bDistChannel)
				{
					//只储存同一通道的数据
					iFrameChID =(pFrame->iFrameType&0x000000ff) -0x30 ;
					iFrameChID = iFrameChID%4;
				}
				else 
				{
					iFrameChID = 0;
				}
				
				iFrameType = pFrame->iFrameType & 0xffffff00;
				iFrameLen = pFrame->iFrameLen & 0x00ffffff ;

#ifdef _DEBUG
				if(iFrameLen > 80000)
				{
					if(iFrameType == 0x62773100 && m_bPCMSound)
					{						
					}
					else
					{
						DebugMsg("FRAME LENGTH IS larger than m_szBuffer size!This program may by wrong!\n");
					}
				}
#endif

				//比较帧数据的长度和剩余缓冲区的大小，保证接下来对帧数据的操作不会出现
				//帧所需要的数据在帧数据缓存所占有的数据长度不够的情况
				// iFrameLen + 200 保证m_szBuffer内数据的长度一定会所需要的帧的数据长
//				if( iFrameLen + 200 > static_cast<int>(m_lDataSize - m_lCurBufferPos))
				if( iFrameLen > static_cast<int>(m_lDataSize - m_lCurBufferPos))
				{
					//如果帧长度不够，则重新读取数据
					if(!OnBufferNoEnough())
					{
						break;
					}
					iCurFilePos = ftell(m_pSFileHandle);
					MyPostMessage( 0, (long)(5 + 30.0*iCurFilePos/iFileTotalLen)); 
				}
				
				pFrame = (FrameHead *)(m_szBuffer+m_lCurBufferPos);
				
				bWriteDecodeAudioBuffer = FALSE;
				
				AddInfoLenth = sizeof(FrameHead);
				iOffset = 0;
				
				if(iFrameType == 0x63643100)		//P Frame
				{					
					*(m_szAviHeader + 0) = 0x30;
					*(m_szAviHeader + 1) = 0x30;
					*(m_szAviHeader + 2) = 0x64;
					*(m_szAviHeader + 3) = 0x63;
					iOffset = GetPFrameOffset(m_szBuffer + m_lCurBufferPos + AddInfoLenth, m_lDataSize - m_lCurBufferPos);
					iFrameLen -= iOffset;
					++m_lTotalFrames[iFrameChID];
				}			
				else if(iFrameType == 0x63643000)	//I Frame
				{
					*(m_szAviHeader + 0) = 0x30;
					*(m_szAviHeader + 1) = 0x30;
					*(m_szAviHeader + 2) = 0x64;
					*(m_szAviHeader + 3) = 0x62; // 0x62;
					iOffset = GetIFrameOffset(m_szBuffer + m_lCurBufferPos + AddInfoLenth, m_lDataSize - m_lCurBufferPos);
					iFrameLen -= iOffset;
					++m_lTotalFrames[iFrameChID];
				}
				else if(iFrameType == 0x62773100)	//A Frame
				{
					*(m_szAviHeader + 0) = 0x30;
					*(m_szAviHeader + 1) = 0x31;
					*(m_szAviHeader + 2) = 0x77;
					*(m_szAviHeader + 3) = 0x62;
					iOffset = GetAFrameOffset(m_szBuffer + m_lCurBufferPos + AddInfoLenth, m_lDataSize - m_lCurBufferPos);
					iFrameLen -= iOffset;
					++m_lTotalFrames[iFrameChID];
					if(m_bPCMSound)
					{
						AddInfoLenth = sizeof(iFrameType);
						*(m_szAviHeader + 4) = 0xfc;
						*(m_szAviHeader + 5) = 0x01;
						*(m_szAviHeader + 6) = 0x00;
						*(m_szAviHeader + 7) = 0x00;
						iFrameLen = 0x01fc;
					}
					else 
					{
						//取得实际的音频数据，并解码，后写入实际的文件长度
						iAudioSize = AUDIO_BUFFER_SIZE;
						//解码音频数据，并取回实际数据和数据的长度
						DecoderAudioData(m_szBuffer + m_lCurBufferPos + AddInfoLenth + iOffset, iFrameLen, szAudioBuffer, iAudioSize);
						*(m_szAviHeader + 4) = iAudioSize&0x000000ff;
						*(m_szAviHeader + 5) = (iAudioSize>>8)&0x000000ff;
						*(m_szAviHeader + 6) = 0x00;
						*(m_szAviHeader + 7) = 0x00;
						m_lTotalLengthAudio[iFrameChID] += iAudioSize;
						bWriteDecodeAudioBuffer = TRUE;
					}
				}

				if (bWriteDecodeAudioBuffer == FALSE)
				{
					*(m_szAviHeader + 4) = iFrameLen&0x000000ff;
					*(m_szAviHeader + 5) = (iFrameLen>>8)&0x000000ff;
					*(m_szAviHeader + 6) = (iFrameLen>>16)&0x000000ff;
					*(m_szAviHeader + 7) = 0x00;
				}
				
				//写文件数据到文件
				//先写头部
				fwrite(m_szAviHeader, 1, m_lHeaderSize, d_fp[iFrameChID]);
				
				//再写帧数据
				if(bWriteDecodeAudioBuffer)
				{
					//再写帧数据
					fwrite(szAudioBuffer, 1, iAudioSize, d_fp[iFrameChID]);	
					packet_size = iAudioSize;
				}
				else
				{
					//再写帧数据
					fwrite(m_szBuffer + m_lCurBufferPos + AddInfoLenth + iOffset, 1, iFrameLen, d_fp[iFrameChID]);
					packet_size = iFrameLen;
				}
				
				//保存文件数据的长度
				lastframe[iFrameChID] = packet_size;
				file_size1[iFrameChID] = file_size2[iFrameChID];
				file_size2[iFrameChID] += (packet_size + 8);
				
				//移动当前数据指针位置
				m_lCurBufferPos = m_lCurBufferPos + AddInfoLenth + iFrameLen + iOffset;
			}
			//如果找不到，则需要重新读取数据
			else
			{
				m_lCurBufferPos = m_lDataSize;
			}
		}
			
		//重置缓存的位置
		if(m_lCurBufferPos >= m_lDataSize)
		{
			m_lCurBufferPos = 0;
			m_lDataSize = 0;
		}
	}
		
	MyPostMessage( 0, 35);
	
	double dStep(0);
	double dProcessPos = 35;
	
	for(int ch = 0 ; ch < m_iFileNum ; ch++)
	{
		GET_EXIT()

		unsigned long cutbyte;	
		fseek(d_fp[ch],0,SEEK_SET);
		fp[ch] = fopen(m_strTFileBody[ch].c_str(), "wb");
		if(fp[ch] == NULL)
		{
			continue;
		}
		
		length = file_size2[ch] / 0x200;
		
		dStep = 25.0/length/m_iFileNum;
		
		//导数据， 
		for(i=0;i<length;i++)
		{
			dProcessPos += dStep;
			MyPostMessage( 0, (long)dProcessPos);
			fread(m_szBuffer, 1, 0x200, d_fp[ch]);
			int kk = GetLastError();
			fwrite(m_szBuffer, 1, 0x200, fp[ch]);	
		}
		

		//最后一帧数据 按4字节 取整
		packet_size = file_size2[ch] - length * 0x200;
		
		cutbyte=packet_size&0x0003;
		packet_size&=0xfffffffc;
		
		lastframe[ch] -=cutbyte;
		fread(m_szBuffer,1,packet_size,d_fp[ch]);
		fwrite(m_szBuffer,1,packet_size,fp[ch]);		
		fseek(fp[ch], file_size2[ch] - lastframe[ch] - cutbyte - 4, SEEK_SET);//modify last frame size to make length mulitple 0f 0x04;
		fwrite(&lastframe[ch],1,4,fp[ch]);
		
		fclose(fp[ch]);
		fp[ch] = NULL;
		fclose(d_fp[ch]);
		d_fp[ch] = NULL;
		dStep = 25.0/m_iFileNum;
		dProcessPos = 35 + (dStep*(ch+1));
		MyPostMessage( 0, (long)dProcessPos);
	}
	
	for(i = 0 ; i < m_iFileNum ; i++)
	{
		if(d_fp[i])
		{
			fclose(d_fp[i]);
			d_fp[i] = NULL;
		}
	}

	fclose(m_pSFileHandle);
	m_pSFileHandle = NULL;
	
	return TRUE; 
		
/*
	FILE *d_fp[MAX_FILE_NUM] = {0};
	FILE *fp[MAX_FILE_NUM] = {0};
//	unsigned char *stream;
	unsigned char *stream_1;
	unsigned long length=0;
	unsigned long packet_flag=0;			//帧类型
	unsigned long packet_size=0;			//帧大小
	unsigned long packet_length=0;			//帧长度
	unsigned long r_ptr;
	unsigned long w_ptr=0;
	unsigned char tmp;
	unsigned long tmp1;
	unsigned long i;
	unsigned long file_size1[MAX_FILE_NUM] = {0};			
	unsigned long file_size2[MAX_FILE_NUM] = {0};			//文件长度
	unsigned long lastframe[MAX_FILE_NUM] = {0};			//最后一帧
    unsigned long tmp_packet_flag = 0;		//临时包的标志

	int			iFrameChID = 0;				//当前帧对应的通道ID
	BOOL		bOpenOK = TRUE;				//打开临时文件是否正常
	for(int j = 0 ; j < m_iFileNum ; j ++)
	{
		m_lTotalFrames[j] = 0;
		d_fp[j] = fopen(m_strTempFile[j], "wb");
		if(d_fp[j] == NULL)
		{
			bOpenOK = FALSE;
			break;
		}
	}

	if(!bOpenOK)
	{
		for(int j = 0 ; j < m_iFileNum ; j++)
		{
			if(d_fp[j])
			{
				fclose(d_fp[j]);
				d_fp[j] = NULL;
			}
		}
		return FALSE;
	}

	int state;

	m_pSFileHandle = fopen(m_strSFileName,"rb");
	if(m_pSFileHandle == NULL)
	{
		for(int j = 0 ; j < m_iFileNum ; j++)
		{
			if(d_fp[j])
			{
				fclose(d_fp[j]);
				d_fp[j] = NULL;
			}
		}
		return FALSE;
	}
	
	int iFileTotalLen(0);	//文件长度
	fseek(m_pSFileHandle, 0, SEEK_END);
	iFileTotalLen = ftell(m_pSFileHandle);
	fseek(m_pSFileHandle, 0, SEEK_SET);
	if(0 == iFileTotalLen)
	{
		for(int j = 0 ; j < m_iFileNum ; j++)
		{
			if(d_fp[j])
			{
				fclose(d_fp[j]);
				d_fp[j] = NULL;
			}
		}
		fclose(m_pSFileHandle);
		return FALSE;
	}

	stream_1 = (unsigned char *)malloc(0x200);
	if(stream_1 == NULL)
	{
		for(int j = 0 ; j < m_iFileNum ; j++)
		{
			if(d_fp[j])
			{
				fclose(d_fp[j]);
				d_fp[j] = NULL;
			}
		}
		fclose(m_pSFileHandle);
		return FALSE;
	}
	
	int iCurFilePos = 0;
	state = 0;

	while(1)
	{
		length = fread(m_szBuffer,1,0x4000,m_pSFileHandle);	

		if(length != 0x4000)
		{
			TRACE("read file over\n");	
			break;
		}

		iCurFilePos = ftell(m_pSFileHandle);
		MyPostMessage( 0, (long)(5 + 30.0*iCurFilePos/iFileTotalLen)); 

		r_ptr = 0;
		while((length) && (r_ptr <= 0x4000))
		{
			switch(state)
			{
			case 0:
				packet_flag = ((unsigned long)*(m_szBuffer + r_ptr++));
				state++;
				length--;
				break;
			case 1:
				packet_flag |= ((unsigned long)*(m_szBuffer + r_ptr++)) << 8;
				state++;
				length--;
				break;
			case 2:
				packet_flag |= ((unsigned long)*(m_szBuffer + r_ptr++)) << 16;
				state++;
				length--;
				break;
			case 3:
				packet_flag |= ((unsigned long)*(m_szBuffer + r_ptr++)) << 24;
				tmp_packet_flag=packet_flag&0xffffff00;
				if(m_bDistChannel)
				{
					//只储存同一通道的数据
					iFrameChID =(packet_flag&0x000000ff) -0x30 ;
					iFrameChID = iFrameChID%4;
				}
				else 
				{
					iFrameChID = 0;
				}
									
				if(tmp_packet_flag == 0x63643100)
				{					
					*(stream_1 + 0) = 0x30;
					*(stream_1 + 1) = 0x30;
					*(stream_1 + 2) = 0x64;
					*(stream_1 + 3) = 0x63;
					state++;
				}
				//else if(packet_flag == 0x62773130)
				else if(tmp_packet_flag == 0x62773100)
				{
					*(stream_1 + 0) = 0x30;
					*(stream_1 + 1) = 0x31;
					*(stream_1 + 2) = 0x77;
					*(stream_1 + 3) = 0x62;
					if(m_bPCMSound)
					{
						*(stream_1 + 0) = 0x30;
						*(stream_1 + 1) = 0x31;
						*(stream_1 + 2) = 0x77;
						*(stream_1 + 3) = 0x62;
						*(stream_1 + 4) = 0xfc;
						*(stream_1 + 5) = 0x01;
						*(stream_1 + 6) = 0x00;
						*(stream_1 + 7) = 0x00;
						w_ptr = 8;
						packet_length = 0x01fc;
						packet_size = packet_length;
						lastframe[iFrameChID] = packet_size;
						state = 8;
						file_size1[iFrameChID] = file_size2[iFrameChID];
						file_size2[iFrameChID] += (packet_size + 8);
					}
					else 
					{
						state++;
					}
				}
				else if(tmp_packet_flag == 0x63643000)
				{
					*(stream_1 + 0) = 0x30;
					*(stream_1 + 1) = 0x30;
					*(stream_1 + 2) = 0x64;
					*(stream_1 + 3) = 0x62;
					state++;
				}
				else
				{
					packet_flag = packet_flag >> 8;
					state = 3;
				}
				length--;
				break;
			case 4:
				tmp = *(m_szBuffer + r_ptr++);
				packet_length = (unsigned long)tmp;
				*(stream_1 + 4) = tmp;
				state++;
				length--;
				break;
			case 5:
				tmp = *(m_szBuffer + r_ptr++);
				packet_length |= (unsigned long)tmp << 8;
				*(stream_1 + 5) = tmp;
				state++;
				length--;
				break;
			case 6:
				tmp = *(m_szBuffer + r_ptr++);
				packet_length |= (unsigned long)tmp << 16;
				*(stream_1 + 6) = tmp;
				state++;
				length--;
				break;
			case 7:	
				tmp = *(m_szBuffer + r_ptr++);
				tmp1=0x00ffffff;
				packet_length |= (unsigned long)tmp << 24;
				packet_length&=tmp1;
				packet_size = packet_length;
				lastframe[iFrameChID] = packet_size;
				*(stream_1 + 7) = 0x00;
				w_ptr = 8;
				state++;
				length--;
				if(tmp_packet_flag == 0x63643000)
				{
					// cut some message
					//调用一个接口取得I帧的偏移位置
					int iOffset = GetIFrameOffset(m_szBuffer + r_ptr, 0x4000 - r_ptr);
					if(iOffset != -1)
					{
						r_ptr += iOffset;
						length -= iOffset;
						m_lTotalFrames[iFrameChID]++;
					}
					else 
					{
						packet_flag = packet_flag >> 8;
						state = 3;
					}
				}
				else if(tmp_packet_flag == 0x63643100)
				{
					// cut some message
					//调用一个接口取得P帧的偏移位置
					int iOffset = GetPFrameOffset(m_szBuffer + r_ptr, 0x4000 - r_ptr);
					if(iOffset != -1)
					{
						r_ptr += iOffset;
						length -= iOffset;
						m_lTotalFrames[iFrameChID]++;
					}
					else
					{
						packet_flag = packet_flag >> 8;
						state = 3;
					}
				}
				if(state != 3)
				{
					file_size1[iFrameChID] = file_size2[iFrameChID];
					file_size2[iFrameChID] += (packet_size + 8);
				}
				break;
			case 8:
				packet_length=0;  
				if(packet_size > 0)
				{
					if(w_ptr >= 0x200)
					{
						fwrite(stream_1,1,0x200,d_fp[iFrameChID]);
						w_ptr = 0;
					}
					*(stream_1 + w_ptr++) = *(m_szBuffer + r_ptr++);
					packet_size--;
					length--;
				}
				else
				{
					fwrite(stream_1,1,w_ptr,d_fp[iFrameChID]);
					state = 0;
				}	
				break;
			}
		}
	}
	
	MyPostMessage( 0, 35);

	double dStep(0);
	double dProcessPos = 35;

	for(int ch = 0 ; ch < m_iFileNum ; ch++)
	{
		unsigned long cutbyte;	
		fseek(d_fp[ch],0,SEEK_SET);
		fp[ch] = fopen(m_strTFileBody[ch], "wb");
		if(fp[ch] == NULL)
		{
			//::MyPostMessage(m_hWnd, m_nMsgID, -1, E_OPEN_TEMPFILE);
			continue;
		}
		length = file_size2[ch] / 0x200;

		dStep = 25.0/length/m_iFileNum;

		for(i=0;i<length;i++)
		{
			dProcessPos += dStep;
			MyPostMessage( 0, (long)dProcessPos);
			fread(m_szBuffer, 1, 0x200, d_fp[ch]);
			fwrite(m_szBuffer, 1, 0x200, fp[ch]);	
		}
		packet_size = file_size2[ch] - length * 0x200;
		
		cutbyte=packet_size&0x0003;
		packet_size&=0xfffffffc;
		
		lastframe[ch] -=cutbyte;
		fread(m_szBuffer,1,packet_size,d_fp[ch]);
		fwrite(m_szBuffer,1,packet_size,fp[ch]);		
		fseek(d_fp[ch], file_size2[ch] - lastframe[ch] - 4, SEEK_SET);//modify last frame size to make length mulitple 0f 0x04;
		fwrite(&lastframe[ch],1,4,fp[ch]);

		fclose(fp[ch]);
		fclose(d_fp[ch]);
		dStep = 25/m_iFileNum;
		dProcessPos = 35 + (dStep*(ch+1));
		MyPostMessage( 0, (long)dProcessPos);
	}

//	::MyPostMessage(m_hWnd, m_nMsgID, 0, 60);

	free(stream_1);
	
	fclose(m_pSFileHandle);
	m_pSFileHandle = NULL;

	return TRUE; */

}

//---------------------------------------------------------------------
//说明：创建文件末尾
//参数：[in]iChID:表示读取第几个通道的数据
//返回：成功返回TRUE，失败返回FALSE
//---------------------------------------------------------------------
BOOL CAviFile::CreateAviTail(int iChID)
{
	FILE *s_fp;
	FILE *d_fp;
	unsigned char *stream;
	unsigned char *stream_1;
	unsigned long file_size = 0;
	unsigned long sizes;
	unsigned long packet_size;
	unsigned char l1,l2,l3,l4;
	unsigned long idx1_size = 0;
	

	//m_strTFileBody[iChID] = "H:\\temp_convert.avib";
	if (m_dp[iChID])
	{
		fclose(m_dp[iChID]);
		m_dp[iChID] = NULL;
	}

	if (GetFileSize(m_strTFileBody[iChID].c_str(), sizes) == FALSE)
		return FALSE;

	s_fp = fopen(m_strTFileBody[iChID].c_str(), "rb");
	if(s_fp == NULL)
	{
		//::MyPostMessage(m_hWnd, m_nMsgID, -1, E_OPEN_TEMPFILE);
		DebugMsg("idex:open source file failed\n");
		return FALSE;
	}

	m_strTFileTail[iChID] = "H:\\temp_convert.avit";
	d_fp = fopen(m_strTFileTail[iChID].c_str(), "wb");
	if(d_fp == NULL)
	{
		//::MyPostMessage(m_hWnd, m_nMsgID, -1, E_OPEN_TEMPFILE);
		DebugMsg("idex:open temporary file failed\n");
		fclose(s_fp);
		return FALSE;
	}

	stream = (unsigned char *)malloc(0x1000);
	if(stream == NULL)
	{
		//::MyPostMessage(m_hWnd, m_nMsgID, -1, E_ALLOC_MEMORY);
		DebugMsg("Memory not enough\n");
		fclose(s_fp);
		fclose(d_fp);
		return FALSE;
	}

	stream_1 = (unsigned char *)malloc(0x200);
	if(stream_1 == NULL)
	{
		//::MyPostMessage(m_hWnd, m_nMsgID, -1, E_ALLOC_MEMORY);
		DebugMsg("Memory 1 not enough\n");
		fclose(s_fp);
		fclose(d_fp);
		free(stream);
		stream = NULL;
		return FALSE;
	}

	*(stream_1 + 0) = 'i';
	*(stream_1 + 1) = 'd';
	*(stream_1 + 2) = 'x';
	*(stream_1 + 3) = '1';
	*(stream_1 + 4) = 0x00;
	*(stream_1 + 5) = 0x00;
	*(stream_1 + 6) = 0x00;
	*(stream_1 + 7) = 0x00;
	fwrite(stream_1,1,8,d_fp);
	file_size = 0;
	while(file_size<sizes)
	{
		fseek(s_fp,file_size,SEEK_SET);
		fread(stream,1,8,s_fp);
	    *(stream_1+0) = *(stream+0);
		*(stream_1+1) = *(stream+1);
		*(stream_1+2) = *(stream+2);
		if (strncmp((char *)stream, "00db", 4) == 0)
			*(stream_1+3) = 'c';
		else
			*(stream_1+3) = *(stream+3);
		file_size += 4;
		if(*(stream+3)=='b')
		{
			*(stream_1+4) = 0x10;
		}
        else 
		{
			*(stream_1+4) = 0x00;
		}
		*(stream_1+5) = 0x00;
		*(stream_1+6) = 0x00;
		*(stream_1+7) = 0x00;
		
		*(stream_1+8) = (unsigned char) (file_size & 0x000000ff);
		*(stream_1+9) = (unsigned char) ((file_size >> 8) & 0x000000ff);
		*(stream_1+10) = (unsigned char) ((file_size >> 16) & 0x000000ff);
		*(stream_1+11) = (unsigned char) ((file_size >> 24) & 0x000000ff); 
		l1 = *(stream+4);
		packet_size = (unsigned long)l1;
		l2 = *(stream+5);
		packet_size |= (unsigned long)l2 << 8;
		l3 = *(stream+6);
		packet_size |= (unsigned long)l3 << 16;
		l4 = *(stream+7);
		packet_size |= (unsigned long)l4 << 24;
		*(stream_1+12) = l1;
		*(stream_1+13) = l2;
		*(stream_1+14) = l3;
		*(stream_1+15) = l4;
		file_size += (packet_size + 4);
		fwrite(stream_1,1,16,d_fp);
		idx1_size += 16;
	}
    char *stream1_flag="00dc";
	       
	if(m_bWriteFlag)
	{
		fseek(d_fp, idx1_size-8, SEEK_SET);
		fwrite(stream1_flag,1,4,d_fp);
	}
	
	*(stream_1+0) = (unsigned char) (idx1_size & 0x000000ff);
	*(stream_1+1) = (unsigned char) ((idx1_size >> 8) & 0x000000ff);
	*(stream_1+2) = (unsigned char) ((idx1_size >> 16) & 0x000000ff);
	*(stream_1+3) = (unsigned char) ((idx1_size >> 24) & 0x000000ff);
	
	fseek(d_fp,4,SEEK_SET);
	fwrite(stream_1,1,4,d_fp);
	
	free(stream_1);
	free(stream);
	fclose(d_fp);
	fclose(s_fp);
	
	return TRUE;
}

//---------------------------------------------------------------------
//说明：把三个文件合并成转换完成的AVI文件
//参数：[in]iChID:表示写第几个通道的数据 0-3
//返回：成功返回TRUE，失败返回FALSE
//---------------------------------------------------------------------
BOOL CAviFile::Link3Files(int iChID)
{
	FILE *s_fp;
	unsigned char *stream;
	unsigned long file_size = 0;
	unsigned long movi_size;
	unsigned long sizes;
	unsigned long tmp;
	int i;

	//目标文件
	m_strDFileName[iChID] = "H:\\temp_convert.avi";
	m_pDFileHandle[iChID] = fopen(m_strDFileName[iChID].c_str(), "wb");
	if (m_pDFileHandle[iChID] == NULL)
	{
		DebugMsg("OpenDeskFile Failed\n");
		return FALSE;
	}

	//先拷头文件
	s_fp = fopen(m_strTFileHead[iChID].c_str(), "rb");
	if(s_fp == NULL)
	{
		DebugMsg("all:open source file 1 failed\n");
		return FALSE;
	}

	stream = (unsigned char *)malloc(0x1000);
	if(stream == NULL)
	{
		fclose(s_fp);
		DebugMsg("Memory not enough\n");
		return FALSE;
	}
	
	fread(stream,1,0x80c,s_fp);
	fwrite(stream,1,0x80c,m_pDFileHandle[iChID]);
	fclose(s_fp);
	file_size += 0x80c;


	//再拷数据帧文件
	if(GetFileSize(m_strTFileBody[iChID].c_str(), sizes) == FALSE)
	{
		free(stream);
		return FALSE;
	}

	file_size += sizes;
	movi_size = sizes;

	s_fp = fopen(m_strTFileBody[iChID].c_str(), "rb");
	if(s_fp == NULL)
	{
		free(stream);
		DebugMsg("all:open source file 2 failed\n");
		return FALSE;
	}

	tmp=sizes/0x800;
	for(i=0;i<(int)tmp;i++)
	{
		fread(stream,1,0x800,s_fp);
		fwrite(stream,1,0x800,m_pDFileHandle[iChID]);
	}
	tmp = sizes - tmp*0x800;
	fread(stream,1,tmp,s_fp);
	fwrite(stream,1,tmp,m_pDFileHandle[iChID]);
	fclose(s_fp);	
	//remove(m_strTFileBody[iChID].c_str());

	//再拷末尾 索引文件
	GetFileSize(m_strTFileTail[iChID].c_str(), sizes);
	file_size += sizes;
	s_fp = fopen(m_strTFileTail[iChID].c_str(), "rb");
	if(s_fp == NULL)
	{
		free(stream);
		DebugMsg("all: open source file 3 failed\n");
		return FALSE;
	}

	tmp = sizes/0x800;
	for(i=0;i<(int)tmp;i++)
	{
		fread(stream,1,0x800,s_fp);
		fwrite(stream,1,0x800,m_pDFileHandle[iChID]);
	}
	tmp = sizes - tmp*0x800;
	fread(stream,1,tmp,s_fp);
	fwrite(stream,1,tmp,m_pDFileHandle[iChID]);
	fclose(s_fp);
	file_size-= 8;
	movi_size += 4;
	
	fseek(m_pDFileHandle[iChID], 4, SEEK_SET);	
	fwrite(&file_size,1,4,m_pDFileHandle[iChID]);  //文件长度
	fseek(m_pDFileHandle[iChID], 0x804, SEEK_SET); //0x7f8 cywang  
	fwrite(&movi_size,1,4,m_pDFileHandle[iChID]);  //帧数据长度
	
	fseek(m_pDFileHandle[iChID],0x30,SEEK_SET);		// cywang
	fwrite(&m_lTotalFrames[iChID], 1, 4, m_pDFileHandle[iChID]);

	int kk = 0;//m_lTotalLengthAudio[iChID] / 2;
	fseek(m_pDFileHandle[iChID],0x108,SEEK_SET);		// cywang
	fwrite(&kk, 1, 4, m_pDFileHandle[iChID]);

	//关闭目标文件
	fclose(m_pDFileHandle[iChID]);
	m_pDFileHandle[iChID] = NULL;
	
	//remove(m_strTempFile[iChID].c_str());
	//remove(m_strTFileTail[iChID].c_str());
	//remove(m_strTFileBody[iChID].c_str());
	//remove(m_strTFileHead[iChID].c_str());
	free(stream);

	return TRUE;
}

//---------------------------------------------------------------------
//说明：转换成MPEG格式的线程体
//参数：无
//返回：正常退出返回0，否则返回1
//---------------------------------------------------------------------
DWORD CAviFile::ChangeToMpeg()
{
	m_bChanging = TRUE;
	FILE *d_fp[MAX_FILE_NUM] = {0};
//	FILE *fp[MAX_FILE_NUM] = {0};
	unsigned long packet_size=0;			//帧大小
	unsigned long i;
	unsigned long file_size1[MAX_FILE_NUM] = {0};			
	unsigned long file_size2[MAX_FILE_NUM] = {0};			//文件长度
	unsigned long lastframe[MAX_FILE_NUM] = {0};			//最后一帧
//	unsigned long lastpacksize = 0;			//最后一个包的大小
    unsigned long tmp_packet_flag = 0;		//临时包的标志

	int			iFrameChID = 0;				//当前帧对应的通道ID
//	BOOL		bFindDistChannel = FALSE;	//是否打到了指定通道的数据，只有在区别通道的情况下使用
	BOOL		bOpenOK = TRUE;				//打开临时文件是否正常


	if(m_pSFileHandle)
	{
		fclose(m_pSFileHandle);
		m_pSFileHandle = NULL;
	}

	m_pSFileHandle = fopen(m_strSFileName.c_str(),"rb");
	if(m_pSFileHandle == NULL)
	{
		MyPostMessage(-1, IDS_CHANGE_FAILED);
		m_bChanging = FALSE;
		return FALSE;
	}
	
	int iFileTotalLen(0);	//文件长度
	fseek(m_pSFileHandle, 0, SEEK_END);
	iFileTotalLen = ftell(m_pSFileHandle);
	fseek(m_pSFileHandle, 0, SEEK_SET);
	if(0 == iFileTotalLen)
	{
		fclose(m_pSFileHandle);
		m_pSFileHandle = NULL;
		m_bChanging = FALSE;
		MyPostMessage(-1, IDS_CHANGE_FAILED);
		return FALSE;
	}

	for(int j = 0 ; j < m_iFileNum ; j ++)
	{
		m_lTotalFrames[j] = 0;
		d_fp[j] = fopen(m_strTempFile[j].c_str(), "wb");
		if(d_fp[j] == NULL)
		{
			bOpenOK = FALSE;
			break;
		}
	}

	if(!bOpenOK)
	{
		for(int j = 0 ; j < m_iFileNum ; j++)
		{
			if(d_fp[j])
			{
				fclose(d_fp[j]);
				d_fp[j] = NULL;
			}
		}
		fclose(m_pSFileHandle);
		m_pSFileHandle = NULL;
		m_bChanging = FALSE;
		MyPostMessage(-1, IDS_CHANGE_FAILED);
		return FALSE;
	}

	int state;
	
	state = 0;
	unsigned long		length = 0;
	int					iCurFilePos = 0;			//当前文件指针的位置
	int					findoff = 0;				//查找帧数据时候的偏移位置
	int					AddInfoLenth = 0;			//偏移位置
	int					iOffset = 0;				//帧数据的偏移位置
	int					iFrameType = 0;				//帧类型
	int					iFrameLen = 0;				//帧长度		
	FrameHead*			pFrame = NULL;				//帧结构定义
	unsigned	char	szAudioBuffer[AUDIO_BUFFER_SIZE] = {0};	//音频数据
	int					iAudioSize = AUDIO_BUFFER_SIZE;			//音频数据的长度
	BOOL				bWriteDecodeAudioBuffer = FALSE;		//是否写解码后的音频数据
	
	MyPostMessage( 0, 5);

	while(1)
	{
		//判断是否退出
		GET_EXIT()

		if(!ReadFileData())
		{
			DebugMsg("read file over\n");	
			break;
		}
		
		iCurFilePos = ftell(m_pSFileHandle);
		MyPostMessage( 0, (long)(5 + 50.0*iCurFilePos/iFileTotalLen)); 
		
		while(m_lCurBufferPos < m_lDataSize  )
		{
			//判断是否退出
			GET_EXIT()
				
			//dvr中会把一个帧凑为8的倍数。
			if(m_lCurBufferPos%8)
			{
				int off = m_lCurBufferPos%8;
				off = 8 - off;
				m_lCurBufferPos += off;
			}

			if(MoveNextFrameHead(m_szBuffer+m_lCurBufferPos, m_lDataSize-m_lCurBufferPos ,&findoff))
			{
				m_lCurBufferPos += findoff;
				m_lCurBufferPos -= 4;
				
				pFrame = (FrameHead *)(m_szBuffer+m_lCurBufferPos);
				//pFrame->iFrameLen = pFrame->iFrameLen&0x00ffffff;

				if(m_bDistChannel)
				{
					//只储存同一通道的数据
					iFrameChID =(pFrame->iFrameType&0x000000ff) -0x30 ;
					iFrameChID = iFrameChID%4;
				}
				else 
				{
					iFrameChID = 0;
				}
				
				iFrameType = pFrame->iFrameType & 0xffffff00;
				iFrameLen = pFrame->iFrameLen & 0x00ffffff ;

				if(iFrameType != 0x62773100 && iFrameLen > 100000)
				{
					DebugMsg("FRAME LENGTH IS ADFKASDLFSDF\n");
				}

				*(m_szAviHeader + 4) = iFrameLen&0x000000ff;
				*(m_szAviHeader + 5) = (iFrameLen>>8)&0x000000ff;
				*(m_szAviHeader + 6) = (iFrameLen>>16)&0x000000ff;
				*(m_szAviHeader + 7) = 0x00;

				//比较帧数据的长度和剩余缓冲区的大小，保证接下来对帧数据的操作不会出现
				//帧所需要的数据在帧数据缓存所占有的数据长度不够的情况
				// iFrameLen + 200 保证m_szBuffer内数据的长度一定会所需要的帧的数据长
				if( iFrameLen + 200 > static_cast<int>(m_lDataSize - m_lCurBufferPos))
				{
					//如果帧长度不够，则重新读取数据
					if(!OnBufferNoEnough())
					{
						break;
					}
					iCurFilePos = ftell(m_pSFileHandle);
					MyPostMessage( 0, (long)(5 + 50.0*iCurFilePos/iFileTotalLen)); 
				}
				
				pFrame = (FrameHead *)(m_szBuffer+m_lCurBufferPos);
				
				bWriteDecodeAudioBuffer = FALSE;
				
				AddInfoLenth = sizeof(FrameHead);
				iOffset = 0;
				
				if(iFrameType == 0x63643100)		//P Frame
				{					
					*(m_szAviHeader + 0) = 0x30;
					*(m_szAviHeader + 1) = 0x30;
					*(m_szAviHeader + 2) = 0x64;
					*(m_szAviHeader + 3) = 0x63;
					//取得数据并写文件
					iOffset = GetPFrameOffset(m_szBuffer + m_lCurBufferPos + AddInfoLenth, m_lDataSize - m_lCurBufferPos);
					
					++m_lTotalFrames[iFrameChID];
				}			
				else if(iFrameType == 0x63643000)	//I Frame
				{
					*(m_szAviHeader + 0) = 0x30;
					*(m_szAviHeader + 1) = 0x30;
					*(m_szAviHeader + 2) = 0x64;
					*(m_szAviHeader + 3) = 0x62;
					//取得数据并写文件
					iOffset = GetIFrameOffset(m_szBuffer + m_lCurBufferPos + AddInfoLenth, m_lDataSize - m_lCurBufferPos);
					
					++m_lTotalFrames[iFrameChID];
				}
				else if(iFrameType == 0x62773100)	//A Frame
				{
					*(m_szAviHeader + 0) = 0x30;
					*(m_szAviHeader + 1) = 0x31;
					*(m_szAviHeader + 2) = 0x77;
					*(m_szAviHeader + 3) = 0x62;
					if(m_bPCMSound)
					{
						AddInfoLenth = sizeof(iFrameType);
						*(m_szAviHeader + 4) = 0xfc;
						*(m_szAviHeader + 5) = 0x01;
						*(m_szAviHeader + 6) = 0x00;
						*(m_szAviHeader + 7) = 0x00;
						iFrameLen = 0x01fc;
					}
					else 
					{
						//取得实际的音频数据，并解码，后写入实际的文件长度
						iAudioSize = AUDIO_BUFFER_SIZE;
						//解码音频数据，并取回实际数据和数据的长度
						DecoderAudioData(m_szBuffer + m_lCurBufferPos + AddInfoLenth, iFrameLen, szAudioBuffer, iAudioSize);
						*(m_szAviHeader + 4) = iAudioSize&0x000000ff;
						*(m_szAviHeader + 5) = (iAudioSize>>8)&0x000000ff;
						*(m_szAviHeader + 6) = 0x00;
						*(m_szAviHeader + 7) = 0x00;
						bWriteDecodeAudioBuffer = TRUE;
					}
				}
				
				//写文件数据到文件
				//先写头部
				fwrite(m_szAviHeader, 1, m_lHeaderSize, d_fp[iFrameChID]);
				
				//再写帧数据
				if(bWriteDecodeAudioBuffer)
				{
					//再写帧数据
					fwrite(szAudioBuffer, 1, iAudioSize, d_fp[iFrameChID]);	
					packet_size = iAudioSize;
				}
				else
				{
					//再写帧数据
					fwrite(m_szBuffer + m_lCurBufferPos + AddInfoLenth + iOffset, 1, iFrameLen, d_fp[iFrameChID]);
					packet_size = iFrameLen;
				}
				
				//保存文件数据的长度
				lastframe[iFrameChID] = packet_size;
				file_size1[iFrameChID] = file_size2[iFrameChID];
				file_size2[iFrameChID] += (packet_size + 8);
				
				//移动当前数据指针位置
				m_lCurBufferPos = m_lCurBufferPos + AddInfoLenth + iFrameLen + iOffset;
			}
			//如果找不到，则需要重新读取数据
			else
			{
				m_lCurBufferPos = m_lDataSize;
			}
		}
			
		//重置缓存的位置
		if(m_lCurBufferPos >= m_lDataSize)
		{
			m_lCurBufferPos = 0;
			m_lDataSize = 0;
		}
	}
	
	MyPostMessage( 0, 55);

	double dStep(0);
	double dProcessPos = 55;


	for(int ch = 0 ; ch < m_iFileNum ; ch++)
	{
		//判断是否退出
		GET_EXIT()

		unsigned long cutbyte;	
		fseek(d_fp[ch],0,SEEK_SET);
		if(!CreateDeskFile(ch))
		{
			fclose(d_fp[ch]);
			d_fp[ch] = NULL;
			remove(m_strTempFile[ch].c_str());
			continue;
		}

		length = file_size2[ch] / 0x200;

		dStep = 45.0/length/m_iFileNum;

		for(i=0;i< length;i++)
		{
			dProcessPos += dStep;
			MyPostMessage( 0, (long)dProcessPos);
			fread(m_szBuffer, 1, 0x200, d_fp[ch]);
			fwrite(m_szBuffer, 1, 0x200, m_pDFileHandle[ch]);	
		}
		packet_size = file_size2[ch] - length * 0x200;
		
		cutbyte=packet_size&0x0003;
		packet_size&=0xfffffffc;
		
		lastframe[ch] -=cutbyte;
		fread(m_szBuffer,1,packet_size,d_fp[ch]);
		fwrite(m_szBuffer,1,packet_size,m_pDFileHandle[ch]);		
		fseek(d_fp[ch], file_size2[ch] - lastframe[ch] - 4, SEEK_SET);//modify last frame size to make length mulitple 0f 0x04;
		fwrite(&lastframe[ch],1,4,m_pDFileHandle[ch]);

		fclose(d_fp[ch]);
		d_fp[ch] = NULL;
		dStep = 45/m_iFileNum;
		dProcessPos = 55 + (dStep*(ch+1));
		MyPostMessage( 0, (long)dProcessPos);

		fclose(m_pDFileHandle[ch]);
		m_pDFileHandle[ch] = NULL;
		remove(m_strTempFile[ch].c_str());
	}

	for(i = 0 ; i < m_iFileNum ; i++)
	{
		if(d_fp[i])
		{
			fclose(d_fp[i]);
			d_fp[i] = NULL;
		}
	}

	if(!GetExit())
	{
		MyPostMessage(0, 100);
	}
	
	fclose(m_pSFileHandle);
	m_pSFileHandle = NULL;
	m_bChanging = FALSE;
	return TRUE;
}

//---------------------------------------------------------------------
//说明：转换成AVI线程体
//参数：无
//返回：正常退出返回0，否则返回1
//---------------------------------------------------------------------
DWORD CAviFile::ChangeToAvi()
{
	BOOL bIsError = FALSE;
	m_bChanging = TRUE;
	MyPostMessage( 0, 5);
	//转换avi文件
	if(CreateAviFile())
	{
		if(!GetExit())
		{
			MyPostMessage(0, 60);
			
			double dStep = 40.0 / m_iFileNum / 4;
			double dPos = 60;
			for(int i = 0 ;  i< m_iFileNum ; i ++)
			{
				//判断退出与否
				GET_EXIT()
					
					//创建avi文件头
					if(CreateAviHeader(i, m_bIsAudio))
					{
						//判断退出与否
						GET_EXIT()
							
							dPos += dStep;
						MyPostMessage(0, (long)dPos);
						
						//创建avi文件尾
						if(CreateAviTail(i))
						{
							//判断退出与否
							GET_EXIT()
								
								dPos += dStep;
							MyPostMessage( 0, (long)dPos);
							
							//创建目标文件
							if(CreateDeskFile(i))
							{
								dPos += dStep;
								MyPostMessage(0, (long)dPos);
								
								//判断退出与否
								GET_EXIT()
									
									//将三个文件都储存成转换后的源文件
									Link3Files(i);
								
								dPos += dStep;
								MyPostMessage( 0, (long)dPos);
								
							}
							else
							{
								bIsError = TRUE;
							}
							//判断退出与否
							GET_EXIT()
						}
						else
						{
							bIsError = TRUE;
						}
					}
					else
					{
						bIsError = TRUE;
					}
			}
			if(GetExit())
			{
				MyPostMessage(0, 100);
			}
		}
	}
	else
	{
		MyPostMessage(-1, IDS_CHANGE_FAILED);
	}

	if(GetExit())
	{
		ClearAllTempFile();
	}
	
	m_bChanging = FALSE;
	if (bIsError)
		return 0;

	return 1;
}


//---------------------------------------------------------------------
//说明：转换线程体
//参数：无
//返回：正常退出返回0，否则返回1
//---------------------------------------------------------------------
DWORD CAviFile::ChangeProcess()
{	
	if(E_CHANGE_AVI == m_eChangeType)
	{
		return ChangeToAvi();
	}
	else if(E_CAHNGE_MPEG == m_eChangeType)
	{
		return ChangeToMpeg();
	}

	return 0;
}

//---------------------------------------------------------------------
//说明：转换线程过渡函数
//参数：无
//返回：正常退出返回0，否则返回1
//---------------------------------------------------------------------
DWORD CAviFile::ChangeThread(LPVOID	lParam)
{
	CAviFile *pThis = (CAviFile *)lParam;

	return pThis->ChangeProcess();
}

//---------------------------------------------------------------------------
//说明：开始转换
//		和文件的类型，最终转换成文件的个数
//参数：[in]strFolder:存放目录
//		[in]hwnd:消息窗口
//		[in]nMsgID:消息ID
//		[in]系统在转换的过程中会不停的向窗口，发送完成的百分比信息
//返回：成功返回TRUE，失败返回FALSE
//---------------------------------------------------------------------
BOOL CAviFile::StartChange(const string& strFolder, HWND hwnd, UINT nMsgID, BOOL bIsAudio, BOOL bIsBlock)
{	
	if(!m_bChanging)
	{
		if(m_hThreadHandle)
		{
			CloseHandle(m_hThreadHandle);
			m_hThreadHandle = NULL;
		}
		
		m_hWnd = hwnd;
		m_nMsgID = nMsgID;
		m_strFolder = strFolder;
		m_bIsAudio = bIsAudio;
		
		ResetEvent(m_hExit);
		
		//创建线程，开始转换
		//typedef unsigned ( __stdcall *start_address )( void * );

		if (bIsBlock)
		{
			return CAviFile::ChangeThread(this);
		}
		else
		{
			m_hThreadHandle = (HANDLE)CreateThread(NULL, 0, CAviFile::ChangeThread, this, 0, &m_dwThreadID);
			if(!m_hThreadHandle)
			{
				DebugMsg("CreateThread Failed!\n");
				return FALSE;
			}
		}
		
		return TRUE;
	}
	return FALSE;
}

//---------------------------------------------------------------------------
//说明：结束转换，如果转换过程中需要停止转换，则调用此接口
//		和文件的类型，最终转换成文件的个数
//参数：[in]strSFile:源文件的名称
//		[in]iFileCount:转换完后，有多少个文件
//返回：成功返回TRUE，失败返回FALSE
//---------------------------------------------------------------------
BOOL CAviFile::StopChange()
{
	if(m_hThreadHandle)
	{
		SetEvent(m_hExit);
		WaitForSingleObject(m_hThreadHandle, INFINITE);
		CloseHandle(m_hThreadHandle);
		m_hThreadHandle = NULL;
		return TRUE;
	}
	return FALSE;
}

//---------------------------------------------------------------------
//说明：取得线程是否需要退出，
//参数：[in]dwWait:等待多长时间
//返回：是返回TRUE，否则返回FALSE
//---------------------------------------------------------------------
BOOL CAviFile::GetExit(DWORD dwWait)
{
	if(WaitForSingleObject(m_hExit, dwWait) == WAIT_OBJECT_0)
	{
		return TRUE;
	}
	return FALSE;
}

//---------------------------------------------------------------------
//说明：修改文件头的信息，在创建完avi(CreateAviHeader)后调用
//参数：[in]header_tb1:头数据
//		[in]iLen:数据长度
//		[in]iChID:通道ID，0-3
//返回：成功返回TRUE，失败返回FALSE
//---------------------------------------------------------------------
BOOL CAviFile::ModifyHeader(unsigned char* header_tb1, int iSize, int iChID)
{
	int iWidth = 704;
	int iHeight = 480;
	switch (m_iTvSystem[iChID])
	{
		case 'N':
			switch (m_iQuality[iChID])
			{
			case '1':
				iWidth = 704;
				iHeight = 480;
				break;
			case '2':
				iWidth = 704;
				iHeight = 240;
				break;
			case '3':
				iWidth = 352;
				iHeight = 240;
				break;
			case '4':
				iWidth = 176;
				iHeight = 120;
				break;
			case '5':
				iWidth = 1920;
				iHeight = 1080;
				break;
			}
			break;
		case 'P':
			switch (m_iQuality[iChID])
			{
			case '1':
				iWidth = 704;
				iHeight = 576;
				break;
			case '2':
				iWidth = 704;
				iHeight = 288;
				break;
			case '3':
				iWidth = 352;
				iHeight = 288;
				break;
			case '4':
				iWidth = 176;
				iHeight = 144;
				break;
			case '5':
				iWidth = 1920;
				iHeight = 1080;
				break;
			}
			break;
	}


	int iFrameSpace = 1000000 / 25;

	header_tb1[0xb0] = iWidth & 0xff; // 0xC0	//BITMAPINFOHEADER	biWidth
	header_tb1[0xb1] = iWidth >> 8 & 0xff; // 0x02
	header_tb1[0xb4] = iHeight & 0xff; // 0xE0	//BITMAPINFOHEADER	biHeight
	header_tb1[0xb5] = iHeight >> 8 & 0xff; // 0x01

	header_tb1[0xa0] = header_tb1[0xb0];
	header_tb1[0xa1] = header_tb1[0xb1];
	header_tb1[0xa2] = header_tb1[0xb4];
	header_tb1[0xa3] = header_tb1[0xb5];

	header_tb1[0x40] = header_tb1[0xb0];
	header_tb1[0x41] = header_tb1[0xb1];
	header_tb1[0x44] = header_tb1[0xb4];
	header_tb1[0x45] = header_tb1[0xb5];

	header_tb1[0xfc] = 0x02;			//dwScale;
	header_tb1[0xfd] = 0x00;
	header_tb1[0xfe] = 0x00;
	header_tb1[0xff] = 0x00;
	header_tb1[0x100] = 0x80;	// 0x40	// 采样率
	header_tb1[0x101] = 0x3e; // 0x1f
	header_tb1[0x102] = 0x00;	// 0x00
	header_tb1[0x103] = 0x00; // 0x00

	header_tb1[0x114] = 0x02; // 采样大小

	WAVEFORMATEX AudioHeader = { 0 };
	AudioHeader.wFormatTag = WAVE_FORMAT_PCM;
	AudioHeader.nChannels = 1;
	AudioHeader.nSamplesPerSec = 8000;
	AudioHeader.nAvgBytesPerSec = AudioHeader.nSamplesPerSec * AudioHeader.nChannels * 2;
	AudioHeader.nBlockAlign = AudioHeader.nChannels * 2;
	AudioHeader.wBitsPerSample = 16;
	AudioHeader.cbSize = 18;
	//wxf memcpy(&header_tb1[0x128], &AudioHeader, sizeof(WAVEFORMATEX));
	memset(&header_tb1[0x128], 0, sizeof(WAVEFORMATEX));

	//header_tb1[0x38] = 2;	 // 流的个数
	header_tb1[0x38] = 1;	 // 流的个数

	header_tb1[0x20] = iFrameSpace & 0xff; // 0x35	33333		//dwMicroSecPerFrame; // 视频帧间隔时间（以毫秒为单位）
	header_tb1[0x21] = iFrameSpace >> 8 & 0xff; // 0x82
	header_tb1[0x22] = iFrameSpace >> 16 & 0xff;
	header_tb1[0x23] = iFrameSpace >> 24 & 0xff;
	header_tb1[0x80] = header_tb1[0x20]; // 0x35 0x76	33333	//dwInitialFrames; // 为交互格式指定初始帧数
	header_tb1[0x81] = header_tb1[0x21]; // 0x82 0x42
	header_tb1[0x82] = header_tb1[0x22]; //
	header_tb1[0x83] = header_tb1[0x23]; // 
	header_tb1[0x84] = 0x40; // 0x40	1000000		//dwScale; // 这个流使用的时间尺度
	header_tb1[0x85] = 0x42; // 0x42
	header_tb1[0x86] = 0x0f; // 0x0f
	header_tb1[0x87] = 0x00; // 
	return TRUE;
}

//---------------------------------------------------------------------------
//说明：取得APP的路径
//参数：无
//返回：返回APP的路径
//---------------------------------------------------------------------
string	CAviFile::GetAppPath()
{
	static string strAppPath;
	if( "" == strAppPath)
	{
		char szPath[MAX_PATH] ={0};
		//GetModuleFileNameA((HMODULE)g_hDllModule, szPath, MAX_PATH - 1);
		GetModuleFileNameA(NULL, szPath, MAX_PATH - 1);
		strAppPath = szPath;
		int iPos = strAppPath.rfind('\\');
		if(iPos > 0)
		{
			strAppPath = strAppPath.substr(0, iPos + 1);
		}

		if("" == strAppPath)
		{
			strAppPath = "C:\\";
		}
	}
	return strAppPath;
}

//---------------------------------------------------------------------
//说明：取得I帧的偏移长度，I帧中可能存在一定的无效数据，因此需要删除
//参数：[in]stream:帧数据
//		[in]iLen:数据长度
//返回：返回I帧的偏移长度
//调用：ChangeFile()中调用
//---------------------------------------------------------------------
int	CAviFile::GetIFrameOffset(unsigned char *stream, int iLen)
{
	return 8;
}

//---------------------------------------------------------------------
//说明：取得P帧的偏移长度，P帧中可能存在一定的无效数据，因此需要删除
//参数：[in]stream:帧数据
//		[in]iLen:数据长度
//返回：返回P帧的偏移长度
//调用：ChangeFile()中调用
//---------------------------------------------------------------------
int	CAviFile::GetPFrameOffset(unsigned char *stream, int iLen)
{
	return 0;
}

//---------------------------------------------------------------------
//说明：取得P帧的偏移长度，P帧中可能存在一定的无效数据，因此需要删除
//参数：[in]stream:帧数据
//		[in]iLen:数据长度
//返回：返回P帧的偏移长度
//调用：ChangeFile()中调用
//---------------------------------------------------------------------
int	CAviFile::GetAFrameOffset(unsigned char *stream, int iLen)
{
	return 0;
}

//---------------------------------------------------------------------------
//说明：向窗口发送消息
//参数：[in]wParam:消息参数
//		[in]lParam:消息参数
//		当wParam为零的时候，lParam表示完成的百分比
//		当wParam为-1时候，lParam表示出错原因
//返回：PostMessage的返回值
//---------------------------------------------------------------------
LRESULT CAviFile::MyPostMessage(WPARAM wParam, LPARAM lParam)
{
	return ::PostMessage(m_hWnd, m_nMsgID, wParam, lParam);
}

//---------------------------------------------------------------------
//说明：当数据缓冲区的长度不够的时候调用,会重新从文件中读取数据
//参数：无
//返回：成功返回TRUE，失败返回FALSE
//---------------------------------------------------------------------
BOOL CAviFile::OnBufferNoEnough()
{
	memcpy(m_szBuffer, m_szBuffer + m_lCurBufferPos, m_lDataSize - m_lCurBufferPos);
	m_lDataSize =  m_lDataSize - m_lCurBufferPos;
	m_lCurBufferPos = 0;
	return ReadFileData();
}

//---------------------------------------------------------------------
//说明：从数据缓冲区中找到一帧的信息
//参数：[in]Date:数据
//		[in]size:数据大小
//		[out]findoff:找到帧数据的偏移位置
//返回：成功返回TRUE，失败返回FALSE
//---------------------------------------------------------------------
BOOL CAviFile::MoveNextFrameHead(unsigned char *Date,int size ,int *findoff)
{
	BOOL	findhead = FALSE;

	int		ptr = 0;

	int		read_byte_count = 0;
	unsigned long	packet_flag;
	unsigned long	temp;

	while( !findhead&& (ptr<size))
	{
		switch(read_byte_count)
		{
		case 0:
			packet_flag = ((unsigned long)*(Date + ptr));
			ptr++;
			read_byte_count++;
			break;
		case 1:
			packet_flag |= ((unsigned long)*(Date + ptr)) << 8;
			ptr++;
			read_byte_count++;
			break;
		case 2:
			packet_flag |= ((unsigned long)*(Date + ptr)) << 16;
			ptr++;
			read_byte_count++;
			break;
		case 3:
			packet_flag |= ((unsigned long)*(Date + ptr)) << 24;
			ptr++;
			temp = packet_flag;
			temp &= 0xffffff00;
				
			if(temp == 0x63643000)
			{
				int asfdl = 1;
			}
			if(temp == 0x63643000 || temp == 0x63643100 
				||	temp == 0x62773100 	)				
			{
				findhead = TRUE;	
			}
			else 
			{
				packet_flag = packet_flag >> 8;
					  read_byte_count = 3;
			}
			
			break;
		}
	}

	*findoff = ptr;

	if(ptr > 8)
	{
		DebugMsg1("lost some date:%d\n",ptr);
	}
	
	return findhead;
}

//---------------------------------------------------------------------
//说明：从文件中读取数据
//参数：无
//返回：成功返回TRUE，失败返回FALSE
//---------------------------------------------------------------------
BOOL CAviFile::ReadFileData()
{
	long lLen = fread(m_szBuffer + m_lDataSize, 1, m_lBufferSize - m_lDataSize, m_pSFileHandle);
	if(lLen == static_cast<int>(m_lBufferSize - m_lDataSize))
	{
		m_lDataSize += lLen;
		return TRUE;
	}
	return FALSE;
}


//---------------------------------------------------------------------
//说明：转换音频数据
//参数：[in]chunk:原始的音频数据
//		[in]chunkLength:原始音频数据大小
//		[in]target:存放转换后的音频数据
//		[in]iTarget:target文件的大小
//返回：成功返回TRUE，失败返回FALSE
//---------------------------------------------------------------------
BOOL CAviFile::DecoderAudioData(unsigned char *chunk, int chunkLength, unsigned char* target, int& iTarget)
{
	return TRUE;
}

//---------------------------------------------------------------------
//说明：取得文件的大小
//参数：[in]szFile:文件名
//		[out]文件大小
//返回：成功返回TRUE，失败返回FALSE
//---------------------------------------------------------------------
BOOL CAviFile::GetFileSize(const char* szFile, unsigned long& ulSize)
{
	FILE* fpTemp = NULL;
	fpTemp = fopen(szFile, "r");
	if(fpTemp)
	{
		fseek(fpTemp, 0, SEEK_END);
		ulSize = ftell(fpTemp);
		fclose(fpTemp);
		fpTemp = NULL;
		return TRUE;
	}
	return FALSE;
}

//---------------------------------------------------------------------
//说明：清除所有的临时文件
//参数：无
//返回：成功返回TRUE，失败返回FALSE
//调用：在用户调用StopChange时，调用
//---------------------------------------------------------------------
BOOL CAviFile::ClearAllTempFile()
{
	for(int i = 0 ; i < MAX_FILE_NUM ; i++)
	{
		try
		{
			remove(m_strTFileHead[i].c_str());
			remove(m_strTFileBody[i].c_str());
			remove(m_strTFileTail[i].c_str());
			remove(m_strTempFile[i].c_str());
		}
		catch(...)
		{
			DebugMsg("remove temp file failed!\n")
		}
	}

	CloseDFileHandle();

	return TRUE;
}

//---------------------------------------------------------------------
//说明：关闭目标文件句柄
//参数：无
//返回：成功返回TRUE，失败返回FALSE
//---------------------------------------------------------------------
BOOL CAviFile::CloseDFileHandle()
{
	for(int i = 0; i< 4; i++)
	{
		if(m_pDFileHandle[i])
		{
			fclose(m_pDFileHandle[i]);
			m_pDFileHandle[i] = NULL;
		}
	}
	return TRUE;
}

//---------------------------------------------------------------------
//说明：转换65xx和m65类型的音频数据
//参数：[in]chunk:原始的音频数据
//		[in]chunkLength:原始音频数据大小
//		[in]target:存放转换后的音频数据
//		[in]iTarget:target文件的大小
//返回：成功返回TRUE，失败返回FALSE
//---------------------------------------------------------------------
BOOL CAviFile::Decoder65AudioData(unsigned char *chunk, int chunkLength, unsigned char* target, int& iTarget)
{
		BYTE *buffer;
	short i;
	int data_size;
	BYTE data[4096];
	BYTE *input_data = NULL;
	short output_sample,delta;
	int index,cur_sample;
	int sb;
	int step,diff;

//	BYTE TempBuffer[10000];
//	
//	memset(TempBuffer,0,10000);
	
	buffer = (BYTE *)target;
	
	index =chunk[1];
	index = (index << 8) & 0xff00;
	
	cur_sample = (chunk[0]&0xff) | (index);
	
	SE_16BIT(cur_sample);
	buffer[1] = (cur_sample >> 8) & 0xff;
	buffer[0] = cur_sample & 0xff;
	
	index = chunk[2];
	
	input_data = (BYTE *)(chunk + 4);
	
	data_size = chunkLength - 4;
	
	for(i=0;i<data_size;i++){
		data[2*i]= input_data[i] & 0x0f;
		data[2*i+1] = (input_data[i] >> 4) & 0x0f;
	}
	
	data_size = data_size * 2;
	step = adpcm_step[index];	
	for(i=0;i<data_size;i++){
		delta = data[i];
		index += adpcm_index[delta];
		CLAMP_0_TO_88(index);
		sb = delta & 8;
		delta &= 7; 
		
		diff = step >> 3;
		if (delta & 4) diff += step;
		if (delta & 2) diff += step >> 1;
		if (delta & 1) diff += step >> 2;
		
		if (sb)
			cur_sample -= diff;
		else
			cur_sample += diff;
		CLAMP_S16(cur_sample);
		output_sample = cur_sample;
		step = adpcm_step[index];
		
		buffer[2*i+2] = output_sample & 0xff;
		buffer[2*i+2+1] = (output_sample >> 8) & 0xff;
	}
	data_size = data_size * 2 + 2;
	
	iTarget = data_size;
	return TRUE;
}
